﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using Inneractive.Nokia.Ad;
using MC.Phone.Ads.Provider;

namespace MC.Phone.Ads.InnerActive
{
    public class InnerActiveAdProvider : BaseAdProvider
    {
        public static readonly DependencyProperty AppProperty =
            DependencyProperty.Register("App", typeof (string), typeof (InnerActiveAdProvider), null);

        [Category("Ad")]
        public string App
        {
            get { return (string) GetValue(AppProperty); }
            set { SetValue(AppProperty, value); }
        }

        public override string Name
        {
            get { return "InnerActive"; }
        }

        public override FrameworkElement ProvideAd()
        {
            var control = new Grid();
            var optionalParams = new Dictionary<InneractiveAd.IaOptionalParams, string>();
            if(!string.IsNullOrWhiteSpace(CountryCode))
                optionalParams.Add(InneractiveAd.IaOptionalParams.Key_Location, CountryCode);

            InneractiveAd.AdReceived += AdReceived;
            InneractiveAd.DefaultAdReceived += DefaultAdReceived;
            InneractiveAd.AdFailed += AdFailed;
            InneractiveAd.AdClicked += AdClicked;
            if (InneractiveAd.DisplayAd(IsTest ? "IA_Test" : App, InneractiveAd.IaAdType.IaAdType_Banner,
                                        control,
                                        60, optionalParams))
            {
                OnNewAd();
            }
            else
            {
                OnNoAd();
            }
            return control;
        }

        private void DefaultAdReceived(object sender)
        {
            OnNewAd();
        }

        private void AdFailed(object sender)
        {
            OnAdError(null);
        }

        private void AdClicked(object sender)
        {
            OnAdEngaged();
        }

        public override void Clean()
        {
        }

        private void AdReceived(object sender)
        {
            OnNewAd();
        }

#if DEBUG
        ~InnerActiveAdProvider()
        {
            Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + "--Finalizing " + GetType().FullName);
        }
#endif
    }
}